package com.collect.collect.api.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.collect.collect.api.entity.DataMonitor;
import com.collect.collect.api.entity.DataMonitorLog;
import com.collect.collect.api.entity.vo.DataMonitorVO;
import com.collect.collect.api.service.IDataMonitorLogService;
import com.collect.collect.api.service.IDataMonitorService;
import com.collect.collect.api.service.ISlaveService;
import com.collect.collect.api.service.ITableFlagService;
import com.collect.collect.api.util.HttpUtils;
import com.collect.collect.api.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.net.ConnectException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Slf4j
@Service
public class SendDataService {

    @Autowired
    private IDataMonitorService dataMonitorService;

    @Autowired
    private ISlaveService slaveService;
    @Autowired
    private IDataMonitorLogService dataMonitorLogService;
    @Autowired
    private ITableFlagService tableFlagService;


    @Value("${hospital-id}")
    private String hospitalId;

    @Value("${data-url}")
    private String dataUrl;

    //批量处理数据最大值
    private static final int batchNum = 50;

    //每30秒执行一次
    @Scheduled(cron = "*/30 * * * * ?")
    public void monitor(){
        log.info("数据同步执行========================");
        log.info("医院id：" + hospitalId);
        List<DataMonitor> dataMonitorList = slaveService.getDataMonitorList10();
        log.info("同步数据条数：" +  dataMonitorList.size());

        for(DataMonitor dataMonitor : dataMonitorList){
            String tableName = dataMonitor.getTableName();

            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("hospital_id",hospitalId);
            paramMap.put("tableName",tableName);

            //更新对象
            DataMonitorLog dataMonitorLog = BeanUtil.copyProperties(dataMonitor,DataMonitorLog.class);
            //程序计数器
            int counter = dataMonitor.getCounter();

            try{
                String flagColumn = tableFlagService.getFlagColumn(tableName);
                if(StringUtils.isBlank(flagColumn)){
                    throw new Exception("表" + tableName + "，标识符号不存在，请到配置表_sync中t_table_flag表添加参数值配置！");
                }

                DataMonitorVO dataMonitorVO = BeanUtil.copyProperties(dataMonitor, DataMonitorVO.class);
                dataMonitorVO.setFlagColumn(flagColumn);
                List<Map<String, Object>> data = dataMonitorService.getData(dataMonitorVO);

                paramMap.put("data",data);
                //查询表的时间类型字段
                Set<String> columnName = dataMonitorService.selectDateColumn(tableName);
                data.forEach(e->{
                    e.put("hospital_id",hospitalId);
                    e.forEach((k,v)->{
                        if(columnName.contains(k) && v != null){
                            //时间转字符串
                            e.put(k,String.valueOf(v));
                        }
                    });
                });
                String result = HttpUtils.sendPost(dataUrl, JSONObject.toJSONString(paramMap) , new HashMap<>());
                log.info(result);
                if(StringUtils.isBlank(result)){
                    throw new ConnectException("数据服务器无法连接，请检查网络配置！");
                }

                JSONObject jsonObject = JSONObject.parseObject(result);
                if(jsonObject != null){
                    int code = (int)jsonObject.get("code");
                    String msg = (String)jsonObject.get("msg");

                    dataMonitorLog.setResultContent("数据平台返回：" + msg);
                    if(code == 200){
                        //同步成功
                        dataMonitorLog.setIsSuccess("1");
                        dataMonitorLogService.saveDataMonitorLog(dataMonitorLog);
                        slaveService.delete(dataMonitor.getMonitorId());
                    }else {
                        //同步失败
                        if(counter < 10){
                            //程序计数器+1
                            slaveService.updateAddCounter(dataMonitor.getMonitorId(),counter);
                        }else{
                            //程序计数到10次失败直接加入日志并删除
                            dataMonitorLog.setIsSuccess("2");
                            dataMonitorLogService.saveDataMonitorLog(dataMonitorLog);
                            slaveService.delete(dataMonitor.getMonitorId());
                        }
                    }
                }
            }catch (Exception e){
                //同步失败
                if(counter < 10){
                    //程序计数器+1
                    slaveService.updateAddCounter(dataMonitor.getMonitorId(),counter);
                }else{
                    //程序计数到10次失败直接加入日志并删除
                    dataMonitorLog.setIsSuccess("2");
                    dataMonitorLog.setResultContent("发送前错误：" + e.getMessage());
                    dataMonitorLogService.saveDataMonitorLog(dataMonitorLog);
                    slaveService.delete(dataMonitor.getMonitorId());
                }
            }


        }

    }
}

